package neu.competition.controller.edge;

import neu.competition.dto.CompetitionsDTO;
import neu.competition.dto.UserDTO;
import neu.competition.service.CompetitionsService;
import neu.competition.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.Comparator;
import java.util.List;

@Controller
@RequestMapping()
public class LoginController {

    @Autowired
    private UserService us;

    @Autowired
    private CompetitionsService competitionsService;

    @GetMapping("/edge/login")
    public String login(Model model) {
        return "user/login";
    }

    @GetMapping("/goForget")
    public String forget() {
        return "user/forgetpassword";
    }

    @RequestMapping("/edge/login_user")
    public String login(String userid, String password, HttpSession session, Model model) {
        UserDTO res = us.login(userid, password);
        if (res == null) {
            model.addAttribute("msg", "账号或密码错误。");
            return "user/login";
        }
        session.setAttribute("USER_INFO", res);

        List<CompetitionsDTO> list = competitionsService.getAllCompetitionsDTOListThree();
        if (list != null) {
            list.sort(Comparator.comparing(CompetitionsDTO::getStartDate, Comparator.nullsLast(Comparator.reverseOrder())));
        }

        model.addAttribute("competitionsDTOS", list);
        return "competition/competition-login";
    }

    @RequestMapping("/edge/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("USER_INFO");
        return "redirect:/";
    }
}